package netWork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class newTcpEchoClient {

    /**
     * 客户端
     *
     */
    //属性,端口号,ip,
    int port;
    String ip;
    Socket socket = null;
    public newTcpEchoClient(int port, String ip) throws IOException {
        this.port = port;
        this.ip = ip;
        socket = new Socket(ip, port);

    }

    //启动客户端
    public void start(){
        System.out.println("客户端启动");

            try(InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                Scanner scanner = new Scanner(System.in);
                Scanner scannerInput = new Scanner(inputStream);
                PrintWriter printWriter = new PrintWriter(outputStream);
                ) {
                while (true) {
                    System.out.println("->");
                    //接受请求
                    String request = scanner.next();
                    //将获取到的请求发送给客户端
                    printWriter.println(request);
                    //清空缓存
                    printWriter.flush();
                    //接受返回的信息
                    String response = scannerInput.next();
                    System.out.printf("[%s : %d]  req: %s resp %s\n", socket.getInetAddress().getHostAddress(), socket.getPort(), request, response);
        }
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
    public static void main(String[] args) throws IOException {
        newTcpEchoClient newTcpEchoClient = new newTcpEchoClient(9999, "127.0.0.1");
        newTcpEchoClient.start();
    }
}
